import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/bloc/follow_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/delete_confirmation_dialog.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/no_data.dart';
import 'package:go_router/go_router.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  int _selectedTabIndex = 0;
  bool _isSwipingLeft = false; // 记录滑动方向

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset('assets/images/commonBg.png', fit: BoxFit.cover),
          ),

          SafeArea(
            bottom: false,
            child: BlocBuilder<AuthCubit, AuthState>(
              builder: (context, authState) {
                if (!authState.isLoggedIn || authState.currentUser == null) {
                  return _buildNotLoggedInView();
                }
                return BlocBuilder<ContentCuratorCubit, ContentCuratorState>(
                  builder: (context, contentState) {
                    return _buildLoggedInView(
                      authState.currentUser!,
                      contentState,
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 未登录状态的视图
  Widget _buildNotLoggedInView() {
    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 39.w),
                Expanded(
                  child: Center(
                    child: MyText(
                      text: "Mine",
                      type: TextType.rubik,
                      fontSize: 26.sp,
                      color: AppColors.black,
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 16.w, 0),
                  child: BlackButton(
                    icon: IconFontIcons.iconSetting,
                    onTap: () => context.push('/profile/settings'),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 100.h),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            padding: EdgeInsets.all(32.w),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              children: [
                Icon(
                  Icons.person_outline,
                  size: 80.w,
                  color: AppColors.textGrey,
                ),
                SizedBox(height: 20.h),
                MyText(
                  text: "Please Login First",
                  type: TextType.rubik,
                  fontSize: 24.sp,
                  color: AppColors.black,
                ),
                SizedBox(height: 12.h),
                MyText(
                  text: "Login to view your profile",
                  type: TextType.miSans,
                  fontSize: 16.sp,
                  color: AppColors.textGrey,
                ),
                SizedBox(height: 32.h),
                GestureDetector(
                  onTap: () => context.push('/auth'),
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    decoration: BoxDecoration(
                      color: AppColors.blue,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Center(
                      child: MyText(
                        text: "Go to Login",
                        type: TextType.miSans,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: AppColors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 600.h),
        ],
      ),
    );
  }

  Widget _buildLoggedInView(
    User currentUser,
    ContentCuratorState contentState,
  ) {
    final userWorks =
        contentState.submissions
            .where((submission) => submission.authorId == currentUser.id)
            .toList();

    final userLikes =
        contentState.submissions
            .where(
              (submission) => submission.isAppreciatedByUser(currentUser.id),
            )
            .toList();

    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 16.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 39.w),
                Expanded(
                  child: Center(
                    child: MyText(
                      text: "Mine",
                      type: TextType.rubik,
                      fontSize: 26.sp,
                      color: AppColors.black,
                    ),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 16.w, 0),
                  child: BlackButton(
                    icon: IconFontIcons.iconSetting,
                    onTap: () => context.push('/profile/settings'),
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 160.h,
            width: double.infinity,
            padding: EdgeInsets.fromLTRB(16.w, 13.h, 16.w, 13.h),
            margin: EdgeInsets.fromLTRB(16.w, 0.h, 16.w, 0.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  width: 122.w,
                  height: 122.w,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(20.r),
                    child: Image.asset(currentUser.avatar, fit: BoxFit.cover),
                  ),
                ),
                SizedBox(width: 22.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Spacer(),
                    MyText(
                      text: currentUser.name,
                      type: TextType.rubik,
                      fontSize: 16.sp,
                      color: AppColors.black,
                    ),
                    const Spacer(),
                    MyText(
                      text: "Ordinary User",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      color: AppColors.textGrey,
                    ),
                    const Spacer(),
                    MyText(
                      text: "Tags:",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      color: AppColors.textGrey,
                    ),
                    const Spacer(),
                    Container(
                      constraints: BoxConstraints(maxWidth: 160.w),
                      child: MyText(
                        text: currentUser.description,
                        type: TextType.miSans,
                        fontSize: 12.sp,
                        color: AppColors.black,
                        maxLines: 4,
                      ),
                    ),
                    const Spacer(),
                  ],
                ),
              ],
            ),
          ),

          Container(
            height: 73.h,
            width: double.infinity,
            margin: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 0.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // work count
                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyText(
                      text: "${userWorks.length}",
                      type: TextType.rubik,
                      fontSize: 24.sp,
                      color: AppColors.black,
                    ),
                    MyText(
                      text: "Work",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.textGrey,
                    ),
                  ],
                ),

                Container(
                  height: 30.h,
                  width: 1,
                  color: AppColors.textGrey.withAlpha(75),
                ),

                // follow count
                BlocBuilder<FollowCubit, FollowState>(
                  builder: (context, followState) {
                    return Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        MyText(
                          text: "${followState.followingUserIds.length}",
                          type: TextType.rubik,
                          fontSize: 24.sp,
                          color: AppColors.black,
                        ),
                        MyText(
                          text: "Follow",
                          type: TextType.miSans,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w900,
                          color: AppColors.textGrey,
                        ),
                      ],
                    );
                  },
                ),

                Container(
                  height: 30.h,
                  width: 1,
                  color: AppColors.textGrey.withAlpha(75),
                ),

                // like count
                Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    MyText(
                      text: "${userLikes.length}",
                      type: TextType.rubik,
                      fontSize: 24.sp,
                      color: AppColors.black,
                    ),
                    MyText(
                      text: "Like",
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w900,
                      color: AppColors.textGrey,
                    ),
                  ],
                ),
              ],
            ),
          ),
          // my work  / my like
          Container(
            width: double.infinity,
            margin: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 16.h),
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              children: [
                // 选项卡
                Padding(
                  padding: EdgeInsets.only(top: 16.h, left: 16.w, right: 16.w),
                  child: _buildTabSelector(),
                ),

                // 添加滑动手势支持和动画切换的内容区域
                GestureDetector(
                  onPanEnd: (details) {
                    // 检测滑动方向
                    if (details.velocity.pixelsPerSecond.dx > 0) {
                      // 向右滑动，切换到 Works (index 0)
                      if (_selectedTabIndex == 1) {
                        setState(() {
                          _isSwipingLeft = false;
                          _selectedTabIndex = 0;
                        });
                      }
                    } else if (details.velocity.pixelsPerSecond.dx < 0) {
                      // 向左滑动，切换到 Like (index 1)
                      if (_selectedTabIndex == 0) {
                        setState(() {
                          _isSwipingLeft = true;
                          _selectedTabIndex = 1;
                        });
                      }
                    }
                  },
                  child: AnimatedSwitcher(
                    duration: const Duration(milliseconds: 300),
                    transitionBuilder: (
                      Widget child,
                      Animation<double> animation,
                    ) {
                      // 根据滑动方向调整动画起始位置
                      final slideOffset =
                          _isSwipingLeft
                              ? const Offset(1.0, 0.0) // 从右侧滑入
                              : const Offset(-1.0, 0.0); // 从左侧滑入

                      return SlideTransition(
                        position: Tween<Offset>(
                          begin: slideOffset,
                          end: Offset.zero,
                        ).animate(
                          CurvedAnimation(
                            parent: animation,
                            curve: Curves.easeInOut,
                          ),
                        ),
                        child: FadeTransition(
                          opacity: Tween<double>(begin: 0.0, end: 1.0).animate(
                            CurvedAnimation(
                              parent: animation,
                              curve: Curves.easeInOut,
                            ),
                          ),
                          child: child,
                        ),
                      );
                    },
                    child: Container(
                      key: ValueKey(_selectedTabIndex),
                      child:
                          _selectedTabIndex == 0
                              ? _buildGridView(userWorks, isWorks: true)
                              : _buildGridView(userLikes, isWorks: false),
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 160.h),
        ],
      ),
    );
  }

  Widget _buildTabSelector() {
    return Row(
      children: [
        // Works
        Expanded(
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isSwipingLeft = false; // 点击切换到 Works，从左侧滑入
                _selectedTabIndex = 0;
              });
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    _selectedTabIndex == 0
                        ? AppColors.tabBlue
                        : Colors.grey.shade100,
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: MyText(
                text: "Works",
                type: TextType.miSans,
                fontSize: 16.sp,
                fontWeight: FontWeight.w900,
                color: AppColors.black,
              ),
            ),
          ),
        ),

        SizedBox(width: 10.w),

        // Like
        Expanded(
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isSwipingLeft = true;
                _selectedTabIndex = 1;
              });
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    _selectedTabIndex == 1
                        ? AppColors.tabBlue
                        : Colors.grey.shade100,
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: MyText(
                text: "Like",
                type: TextType.miSans,
                fontSize: 16.sp,
                fontWeight: FontWeight.w900,
                color: AppColors.black,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildGridView(List<ContentSubmission> data, {bool isWorks = true}) {
    return data.isEmpty
        ? Padding(
          padding: EdgeInsets.only(bottom: 66.h),
          child: Center(
            child: NoData(
              width: 164.w,
              height: 164.w,
              text: isWorks ? 'No works yet' : 'No liked content yet',
            ),
          ),
        )
        : Padding(
          padding: EdgeInsets.all(16.w),
          child: MasonryGridView.count(
            crossAxisCount: 2,
            mainAxisSpacing: 16.h,
            crossAxisSpacing: 16.w,
            shrinkWrap: true,
            physics: const ClampingScrollPhysics(),
            itemCount: data.length,
            itemBuilder: (context, index) {
              return _buildMediaItem(data[index], isWorks);
            },
          ),
        );
  }

  Widget _buildMediaItem(ContentSubmission submission, bool isWorks) {
    final mediaAsset =
        submission.mediaAssets.isNotEmpty ? submission.mediaAssets.first : null;

    final isVideo = mediaAsset?.mediaType == ContentMediaType.videoClip;
    final imagePath =
        isVideo ? mediaAsset?.thumbnailPath : mediaAsset?.localPath;

    return GestureDetector(
      onTap: () {
        context.push('/discovery/share/${submission.submissionId}');
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16.r),
        child: AspectRatio(
          aspectRatio: 147 / 199,
          child: Container(
            decoration: BoxDecoration(color: AppColors.blue.withAlpha(110)),
            child: Stack(
              fit: StackFit.expand,
              children: [
                // 图片
                if (imagePath != null)
                  _buildImageWidget(imagePath)
                else
                  Container(
                    color: AppColors.blue.withAlpha(75),
                    child: Center(
                      child: Icon(
                        Icons.image_not_supported,
                        color: AppColors.white,
                        size: 32.w,
                      ),
                    ),
                  ),

                if (isVideo)
                  Center(
                    child: Icon(
                      IconFontIcons.iconPlay,
                      color: AppColors.white,
                      size: 40.w,
                    ),
                  ),

                if (isWorks)
                  Positioned(
                    top: 8.h,
                    right: 8.w,
                    child: GestureDetector(
                      onTap: () async {
                        final shouldDelete =
                            await DeleteConfirmationHelper.showDeleteWorkConfirmation(
                              context: context,
                            );

                        if (shouldDelete == true && mounted) {
                          final cubit = context.read<ContentCuratorCubit>();
                          final success = await cubit.deleteSubmission(
                            submission.submissionId,
                          );

                          if (success) {}
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(6.w),
                        decoration: BoxDecoration(
                          color: AppColors.tabBlue,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          IconFontIcons.iconTrashFill,
                          color: AppColors.black,
                          size: 16.w,
                        ),
                      ),
                    ),
                  ),
                Positioned(
                  bottom: 8.h,
                  right: 8.w,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 8.w,
                      vertical: 4.h,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.white.withAlpha(50),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          isWorks
                              ? IconFontIcons.iconPlayFill
                              : IconFontIcons.iconHeart,
                          color: isWorks ? AppColors.white : AppColors.red,
                          size: isWorks ? 12.w : 18.w,
                        ),
                        SizedBox(width: 4.w),
                        MyText(
                          text:
                              isWorks ? "0" : "${submission.appreciationCount}",
                          type: TextType.miSans,
                          fontSize: 12.sp,
                          color: AppColors.white,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildImageWidget(String imagePath) {
    if (imagePath.startsWith('/') ||
        imagePath.contains('Documents') ||
        imagePath.contains('thumbnails')) {
      return Image.file(
        File(imagePath),
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildImageErrorWidget();
        },
      );
    } else {
      return Image.asset(
        imagePath,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return _buildImageErrorWidget();
        },
      );
    }
  }

  /// 构建图片加载错误时的占位符
  Widget _buildImageErrorWidget() {
    return Container(
      color: AppColors.blue.withAlpha(75),
      child: Center(
        child: Icon(
          Icons.image_not_supported,
          color: AppColors.white,
          size: 32.w,
        ),
      ),
    );
  }
}
